package cn.touna.jss.modules.third.zhima.client;


import cn.touna.jss.common.enums.ChannelTypeEnum;
import cn.touna.jss.common.properties.disconf.ZhimaProperties;
import cn.touna.jss.modules.third.zhima.entity.AccreditCallbackDto;
import cn.touna.jss.modules.third.zhima.entity.AccreditDto;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.antgroup.zmxy.openplatform.api.DefaultZhimaClient;
import com.antgroup.zmxy.openplatform.api.ZhimaApiException;
import com.antgroup.zmxy.openplatform.api.request.ZhimaAuthInfoAuthorizeRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 生成PC端页面授权的URL，证件号，姓名授权入参
 * </P>
 *
 * @author tianhuaxing 2017年5月22日 下午8:02:06
 * @since 1.0.0.000
 */
@Component
public class PCH5PageAuthClient {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ZhimaProperties zhimaProperties;

    public String generatePcPageAuthUrl(AccreditDto dto) throws ZhimaApiException {
        ZhimaAuthInfoAuthorizeRequest req = new ZhimaAuthInfoAuthorizeRequest();
        // 授权来源渠道设置为appp
        if (ChannelTypeEnum.CHANNEL_H5.getId().equals(dto.getChannel())) {
            req.setChannel(ChannelTypeEnum.CHANNEL_H5.getName());
        } else if (ChannelTypeEnum.CHANNEL_PC.getId().equals(dto.getChannel())) {
            req.setChannel(ChannelTypeEnum.CHANNEL_PC.getName());
        }
        // 授权类型设置为2标识为证件号授权见“章节4中的业务入参说明identity_type”
        req.setIdentityType(zhimaProperties.getIdentityType());
        // 构造授权业务入参证件号，姓名，证件类型;“章节4中的业务入参说明identity_param”
        Map<String, String> identityParams = new HashMap<String, String>();
        identityParams.put("certNo", dto.getIdCard());
        identityParams.put("name", dto.getName());
        identityParams.put("certType", zhimaProperties.getCertType());
        req.setIdentityParam(JSONObject.toJSONString(identityParams));

        // 构造业务入参扩展参数“章节4中的业务入参说明biz_params”
        Map<String, String> bizParams = new HashMap<String, String>();
        Map<String, String> stateMap = new HashMap<String, String>();
        stateMap.put("name", dto.getName());
        stateMap.put("certNo", dto.getIdCard());
        stateMap.put("url", dto.getState());
        stateMap.put("businessId", dto.getBusinessId());
        stateMap.put("userId", dto.getUserId());
        bizParams.put("state", JSON.toJSONString(stateMap));
        if (ChannelTypeEnum.CHANNEL_H5.getId().equals(dto.getChannel())) {
            bizParams.put("auth_code", ChannelTypeEnum.CHANNEL_H5.getId());
            bizParams.put("channelType", ChannelTypeEnum.CHANNEL_H5.getName());
        } else if (ChannelTypeEnum.CHANNEL_PC.getId().equals(dto.getChannel())) {
            bizParams.put("auth_code", ChannelTypeEnum.CHANNEL_PC.getId());
            bizParams.put("channelType", ChannelTypeEnum.CHANNEL_PC.getName());
        }
        req.setBizParams(JSONObject.toJSONString(bizParams));
        DefaultZhimaClient client = new DefaultZhimaClient(zhimaProperties.getGatewayUrl(), zhimaProperties.getAppId(),
                zhimaProperties.getPrivateKey(), zhimaProperties.getZhimaPublicKey());
        logger.info("【调用芝麻授权】芝麻返回结果:{}", client.generatePageRedirectInvokeUrl(req));
        return client.generatePageRedirectInvokeUrl(req);
    }

    /**
     * 从回调地址中获取返回值.
     *
     * @param dto
     * @throws Exception
     */
    public Map<String, String> parseFromReturnUrl(AccreditCallbackDto dto) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        // 判断串中是否有%，有则需要decode
        String params = URLDecoder.decode(dto.getParams(), zhimaProperties.getCharset());
        String sign = URLDecoder.decode(dto.getSign(), zhimaProperties.getCharset());
        DefaultZhimaClient client = new DefaultZhimaClient(zhimaProperties.getGatewayUrl(), zhimaProperties.getAppId(),
                zhimaProperties.getPrivateKey(), zhimaProperties.getZhimaPublicKey());
        String resultString = client.decryptAndVerifySign(params, sign);
        String[] resultArray = resultString.split("&");
        for (String result : resultArray) {
            String[] splits = result.split("=");
            if (splits.length >= 2) {
                map.put(splits[0], splits[1]);
            }
        }
        logger.info("【认证中心-芝麻授权回调解密】授权解密param的参数:{}", JSON.toJSON(map));
        return map;
    }


}
